package com.cy.controller;

import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;

import com.cy.annotation.SysLog;
import com.cy.entity.Member;
import com.cy.entity.SysConfig;
import com.cy.enumresource.StateEnum;
import com.cy.service.SysConfigService;
import com.cy.util.ExportExcel;
import com.cy.utils.*;
import com.cy.vo.MemberVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cy.service.MemberService;
import org.springframework.web.multipart.MultipartFile;


/**
 * 
 * 
 * @author chenyi
 * @email qq228112142@qq.com
 * @date 2017-08-08 17:35:59
 */
@Controller
@RequestMapping("member")
public class MemberController {

	private static final Logger log = Logger.getLogger("MemberController");

	@Autowired
	private MemberService memberService;
	@Autowired
	private SysConfigService sysConfigService;

	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	@RequiresPermissions("member:list")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);

		List<Member> memberList = memberService.queryList(query);

		//获取推荐一人奖励的云币
		int defaultCoin=10000;
		List<SysConfig> config=sysConfigService.findByCode("cfg_default_coin");
		if(config!=null&&config.size()>0){
			defaultCoin=Integer.parseInt(config.get(0).getValue());
		}
		//设置云币相关数据
		for(int i=0;i<memberList.size();i++){
			long totalCoin=memberList.get(i).getRecommendLowerNumber()*defaultCoin;
			long getCoin=memberList.get(i).getGetCoin();
			//设置预计收入云币
			memberList.get(i).setTotalCoin(totalCoin);
			//设置未充值云币
			memberList.get(i).setUnGetCoin(totalCoin-getCoin);

		}
		int total = memberService.queryTotal(query);

		PageUtils pageUtil = new PageUtils(memberList, total, query.getLimit(), query.getPage());

		return R.ok().put("page", pageUtil);
	}
	
	/**
	 * 通过推荐上级云支付账号查询
	 */
    @ResponseBody
	@RequestMapping("/findByRecommendAccount/{recommendAccount}")
	@RequiresPermissions("member:list")
	public R findByAccount(@RequestParam Map<String, Object> params,@PathVariable String recommendAccount){
		params.put("recommendAccount",recommendAccount);
		//查询列表数据
        Query query = new Query(params);

		List<Member> memberList = memberService.queryList(query);
		int total = memberService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(memberList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}

	/**
	 * 通过推荐上级云支付账号查询
	 */
	@ResponseBody
	@RequestMapping("/findByTeamParentAccount/{teamParentAccount}")
	@RequiresPermissions("member:list")
	public R findByTeamParentAccount(@RequestParam Map<String, Object> params,@PathVariable String teamParentAccount){
		params.put("teamParentAccount",teamParentAccount);
		//查询列表数据
		Query query = new Query(params);

		List<Member> memberList = memberService.queryList(query);
		int total = memberService.queryTotal(query);

		PageUtils pageUtil = new PageUtils(memberList, total, query.getLimit(), query.getPage());

		return R.ok().put("page", pageUtil);
	}
	/**
	 * 启用
	 */
	@ResponseBody
	@SysLog("启用会员")
	@RequestMapping("/enable")
	@RequiresPermissions("member:update")
	public R enable(@RequestBody Long[] ids){
		String stateValue= StateEnum.ENABLE.getCode();
		memberService.updateState(ids,stateValue);
		return R.ok();
	}
	/**
	 * 禁用
	 */
	@ResponseBody
	@SysLog("禁用会员")
	@RequestMapping("/limit")
	@RequiresPermissions("member:update")
	public R limit(@RequestBody Long[] ids){
		String stateValue=StateEnum.LIMIT.getCode();
		memberService.updateState(ids,stateValue);
		return R.ok();
	}
	/**
	 * 导出
	 */
	@ResponseBody
	@SysLog("导出会员")
	@RequestMapping("/export")
	@RequiresPermissions("member:list")
	public R export(@RequestParam Map<String, Object> params, HttpServletResponse response){

		ExportExcel<MemberVo> ex = new ExportExcel<MemberVo>();
		String[] headers =
				{ "云支付账号", "姓名", "电话", "推荐码", "团队码","状态","缴费时间","缴费金额","推荐人云支付账号","推荐下级人数","预计收入(元)","已充值(元)","未充值(元)"};
		List<MemberVo> data = memberService.exportList();
		List<SysConfig> configs=sysConfigService.findByCode("cfg_default_coin");
		int defaultCoin=10000;
		if(configs!=null&&configs.size()>0){
			defaultCoin=Integer.parseInt(configs.get(0).getValue());
		}
		for (int i=0;i<data.size();i++){
			//设置预计收入云币
			data.get(i).setTotalCoin(data.get(i).getRecommendLowerNumber()*defaultCoin);
			//设置未充值云币
			data.get(i).setUnGetCoin(data.get(i).getTotalCoin()-data.get(i).getGetCoin());
		}
		try
		{
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			String fileName="会员列表"+sdf.format(new Date())+".xls";
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
			ServletOutputStream outputStream = response.getOutputStream();
			ex.exportExcel(fileName,headers, data, outputStream,"yyyy-MM-dd HH:mm:ss");
			outputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return R.ok();
	}


	@ResponseBody
	@SysLog("导入会员")
	@RequestMapping("/importExcel")
	public R importExcel(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		String fileName=file.getOriginalFilename();
		String _extName = fileName.substring(fileName.indexOf("."),fileName.length());//获取扩展名
		if(!".xls".equals(_extName)){
			throw new RRException("请上传xls文件");
		}
		memberService.importXls(file);

		return R.ok();
	}

	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/teamList/{teamCode}")
	@RequiresPermissions("member:list")
	public R teamList(@RequestParam Map<String, Object> params,@PathVariable("teamCode") String teamCode){
		params.put("teamCode",teamCode);
		//查询列表数据
		Query query = new Query(params);

		List<Member> memberList = memberService.queryList(query);
		int total = memberService.queryTotal(query);

		PageUtils pageUtil = new PageUtils(memberList, total, query.getLimit(), query.getPage());

		return R.ok().put("page", pageUtil);
	}

    /**
     * 跳转到新增页面
     **/
    @RequestMapping("/add")
    @RequiresPermissions("member:save")
    public String add(){
        return "member/add.jsp";
    }

    /**
     *   跳转到修改页面
     **/
    @RequestMapping("/edit/{id}")
    @RequiresPermissions("member:update")
    public String edit(HttpServletRequest request, Model model, @PathVariable("id") Long id){
			Member member = memberService.queryObject(id);
        model.addAttribute("model", member);
        return "member/edit.jsp";
    }

	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("member:info")
	public String info(Model model,@PathVariable("id") Long id){
		Member member = memberService.queryObject(id);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateStr=sdf.format(member.getPayTime());
		member.setDateStr(dateStr);
		model.addAttribute("model",member);
		return "member/info.jsp";
	}
	
	/**
	 * 保存
	 */
    @ResponseBody
	@SysLog("保存会员")
	@RequestMapping("/save")
	@RequiresPermissions("member:save")
	public R save(@RequestBody Member member){
		memberService.save(member);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
    @ResponseBody
	@SysLog("修改会员")
	@RequestMapping("/update")
	@RequiresPermissions("member:update")
	public R update(@RequestBody Member member){
		memberService.update(member);
		
		return R.ok();
	}
	
	/**
	 * 删除
	 */
    @ResponseBody
	@SysLog("删除会员")
	@RequestMapping("/delete")
	@RequiresPermissions("member:delete")
	public R delete(@RequestBody Long[] ids){
		memberService.deleteBatch(ids);
		
		return R.ok();
	}

	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/init")
	public R init(){
		List<Member> list = memberService.queryList(null);
		for(int i=0;i<list.size();i++){
			Map<String, Object> params =new HashMap<>();
			params.put("recommendAccount",list.get(i).getAccount());
			//获取下级
			int count= memberService.queryTotal(params);
			list.get(i).setRecommendLowerNumber(count);
			memberService.update(list.get(i));
		}
		return R.ok();
	}
}
